package com.bowen.cbs.common;

import com.alibaba.fastjson.JSON;
import com.bowen.cbs.vo.FileLogVO;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * 读取前置机日志
 * 公众号【猿码天地】
 */
public class FrontEndLogFile {

	/**
	 * 读取前置机日志
	 * @param fileLogVO
	 * @return
	 */
	public static String readFile(FileLogVO fileLogVO) {
		if (null == fileLogVO.getLogFile() || "" == fileLogVO.getLogFile().trim()) {
			return "请指定目录文件";
		}
		String filePath = fileLogVO.getLogFile();
		FileChannel fcin = null;
		List<String> logs = new ArrayList<>();
		try {
			File logFile = new File(filePath);
			if (logFile.isDirectory()) {
				return "请指定具体目录文件";
			}
			if (!logFile.exists()) {
				return "请指定目录文件：" + filePath + "不存在！";
			}
			int bufSize = 1024 * 1024 * 5;
			fcin = new RandomAccessFile(logFile, "r").getChannel();
			long fsize = fcin.size();
			long line = Long.valueOf(String.valueOf(null == fileLogVO.getLine() ? 2000 : fileLogVO.getLine()));
			if(fsize - line > 0){
				fcin.position(fsize - line);
			}
			ByteBuffer rBuffer = ByteBuffer.allocate(bufSize);
			String enterStr = "\n";
			byte[] bs = new byte[bufSize];
			String tempString = null;
			//通过通道读到buffer中去
			while (fcin.read(rBuffer) != -1) {
				//position可以视为游标的作用,默认读后在尾部获得buffer大小
				int rSize = rBuffer.position();
				//将position设为0
				rBuffer.rewind();
				//将buffer中的数据转化成byte数组
				rBuffer.get(bs);
				rBuffer.clear();
				//转化成字符串
				tempString = new String(bs, 0, rSize, Charset.forName("GB2312"));
				int fromIndex = 0;
				int endIndex = 0;
				//对数据进行分行,即endIndex指向换行符
				while ((endIndex = tempString.indexOf(enterStr, fromIndex)) != -1) {
					String recordStr = tempString.substring(fromIndex, endIndex);
					if(StringUtils.hasText(recordStr)) {
						if(recordStr.indexOf("\r") != -1){
							recordStr = recordStr.replaceAll("\r","");
						}
						logs.add(recordStr);
					}
					fromIndex = endIndex + 1;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fcin != null) {
				try {
					fcin.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return JSON.toJSONString(logs);
	}

}